<template>
  <div class="wrap-container">
    <div class="stadium_detail">
      <div class="detail_l">
        <div style="display: flex">
          <div style="margin-right: 15px; flex: 1">
            <div class="bg-white py-3 px-4">
              <div class="flex justify-between">
                <div class="manage_tit">
                  <div class="line"></div>
                  <p>场馆详情</p>
                </div>
                <div class="approval_btn">
                  <el-button @click="goBack" size="small">返回</el-button>
                </div>
              </div>
            </div>
            <div class="stadium_info dis_flex">
              <div class="stadium_img">
                <img :src="details.imgStr" alt="" />
              </div>
              <div class="stadium_cont">
                <div class="stadium_top flexBetween">
                  <div class="stadium_name dis_flex">
                    <p>{{ details.stadiumName }}</p>
                    <div class="auth_box" v-if="details.approval == 1">
                      <img src="@/assets/images/icon/auth_icon.png" alt="" />
                      <span>已认证</span>
                    </div>
                  </div>
                  <div
                    class="edit"
                    v-hasPermi="['sys:stadium:btn_update']"
                    @click="handleEditStadium"
                  >
                    <img src="@/assets/images/icon/edit_icon.png" alt="" />
                    <span>编辑</span>
                  </div>
                </div>
                <div class="rate">
                  <el-rate
                    v-model="details.star"
                    disabled
                    show-score
                    text-color="#FFC300"
                    :colors="['#FF8D1A', '#FF8D1A', '#FF8D1A']"
                    disabled-void-color="#E5E5E5"
                  >
                  </el-rate>
                </div>
                <div class="stadium_box">
                  <div class="stadium_l">
                    <div class="info_item">
                      <p class="info_label">场馆类型</p>
                      <p>{{ details.stadiumTypeName }}</p>
                    </div>
                    <div class="info_item">
                      <p class="info_label">营业时间</p>
                      <p>
                        <span>{{ details.workDate }}</span>
                        <span style="margin-left: 10px">{{ details.legalDate }}</span>
                      </p>
                    </div>
                    <div class="info_item">
                      <p class="info_label">门店电话</p>
                      <p>
                        <img src="@/assets/images/icon/phone_icon.png" />
                        <span>{{ details.phone }}</span>
                      </p>
                    </div>
                    <div class="info_item">
                      <p class="info_label">门店地址</p>
                      <p>
                        <img src="@/assets/images/icon/map_icon.png" />
                        <span>{{ details.gdAddress }}</span>
                      </p>
                    </div>
                    <div class="info_item">
                      <p class="info_label">所属机构</p>
                      <p>{{ details.enterpriseName }}</p>
                    </div>
                  </div>
                  <div class="stadium_r dis_flex" style="width: 45%">
                    <p class="info_label">场馆服务</p>
                    <div class="service_list">
                      <div class="service_item" v-for="(item, index) in serviceList" :key="index">
                        <div class="service_info">
                          <p>
                            <img :src="item.url" alt="" />
                          </p>
                          <span>{{ item.name }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="detail_r">
            <div class="detail_item">
              <div class="detail_tit">
                <div class="tit_name">
                  <div class="line"></div>
                  <span>数据概况</span>
                </div>
                <p @click="handleMore">查看更多</p>
              </div>
              <el-row class="data_list" :gutter="14">
                <el-col :span="8">
                  <div class="data_info">
                    <p class="data_label">今日浏览</p>
                    <p class="data_num">{{ profileData.viewCount }}</p>
                    <div class="compare">
                      较昨日
                      <p>
                        <span
                          :class="{
                            up_style: profileData.viewStatus == 1,
                            drop_style: profileData.viewStatus == 2,
                          }"
                          >{{ profileData.viewRate }}</span
                        >
                        <img
                          :src="profileData.viewStatus == 1 ? upIcon : dropIcon"
                          alt=""
                          v-if="profileData.viewStatus != 0"
                        />
                      </p>
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="data_info">
                    <p class="data_label">今日预约</p>
                    <p class="data_num">{{ profileData.orderCount }}</p>
                    <div class="compare">
                      较昨日
                      <p>
                        <span
                          :class="{
                            up_style: profileData.orderStatus == 1,
                            drop_style: profileData.orderStatus == 2,
                          }"
                          >{{ profileData.orderRate }}</span
                        >
                        <img
                          :src="profileData.orderStatus == 1 ? upIcon : dropIcon"
                          alt=""
                          v-if="profileData.orderStatus != 0"
                        />
                      </p>
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="data_info">
                    <p class="data_label">今日收藏</p>
                    <p class="data_num">{{ profileData.likeCount }}</p>
                    <div class="compare">
                      较昨日
                      <p>
                        <span
                          :class="{
                            up_style: profileData.likeStatus == 1,
                            drop_style: profileData.likeStatus == 2,
                          }"
                          >{{ profileData.likeRate }}</span
                        >
                        <img
                          :src="profileData.likeStatus == 1 ? upIcon : dropIcon"
                          alt=""
                          v-if="profileData.likeStatus != 0"
                        />
                      </p>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="detail_item reservate_box">
              <div class="detail_tit">
                <div class="tit_name">
                  <div class="line"></div>
                  <span>预约信息</span>
                </div>
                <p @click="handleMore">查看更多</p>
              </div>
              <div class="reservate_list">
                <div class="reservate_item" v-for="item in reservateList" :key="item.id">
                  <p class="reservate_date">{{ item.createTime }}</p>
                  <p class="reservate_txt">
                    用户{{ item.orderPhone }}预定了{{ item.siteName }}，订单号：{{ item.orderNo }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <site-bulletin
            :stadiumId="stadiumId"
            :stadiumData="stadiumData"
            ref="siteBulletinRef"
            :orderDate="todayDate"
            :orderStadiumType="siteParams.type"
          ></site-bulletin>
        </div>
        <div class="detail_r">
          <div class="detail_item comment_box">
            <div class="detail_tit">
              <div class="tit_name">
                <div class="line"></div>
                <span>评论留言</span>
              </div>
              <p @click="handleMore">查看更多</p>
            </div>
            <div class="comment_list">
              <div class="comment_item" v-for="item in commentList" :key="item.id">
                <div class="head_img">
                  <img :src="item.headImg" />
                </div>
                <div class="comment_info">
                  <div class="comment_name">
                    <div class="username">{{ item.realName }}</div>
                  </div>
                  <div class="comment_date">{{ item.createTime }}</div>
                  <div class="comment_rate">
                    <el-rate
                      v-model="item.star"
                      disabled
                      :colors="['#FF8D1A', '#FF8D1A', '#FF8D1A']"
                      disabled-void-color="#E5E5E5"
                    >
                    </el-rate>
                  </div>
                  <div class="comment_txt">{{ item.content }}</div>
                  <div class="img_box" v-if="item.imgs.length > 0">
                    <div
                      class="img_item"
                      v-for="(subItem, index) in item.imgs"
                      :key="index"
                      :preview-src-list="subItem.imgs"
                    >
                      <el-image :src="subItem"></el-image>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <edit-stadium :show="showEditStadium" :stadiumId="stadiumId" @close="closeStadiumDialog()" />
    <el-dialog
      v-model="showTipsModal"
      width="500px"
      custom-class="tip_dialog"
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="tip_tit">提示</div>
      <div class="tip_cont">{{ tipCont }}</div>
      <div class="tip_btn" @click="showTipsModal = false">知道了</div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed, onMounted, onBeforeMount } from 'vue'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import { getWeekDates, type WeekDateItem } from '@/utils/index'
import {
  getStadiumById,
  getDataProfiling,
  getOrderListByStadiumId,
  getEvaluateListByStadiumId,
} from '@/api/stadium/stadium'
import EditStadium from '@/components/Stadium/editStadium.vue'
import SiteBulletin from '@/components/Stadium/siteBulletin.vue'
import upIcon from '@/assets/images/icon/up_icon.png'
import dropIcon from '@/assets/images/icon/drop_icon.png'
import { useStore } from 'vuex'
import dayjs from 'dayjs'
import { useFromRoute } from '@/composables/useFromRoute'
// import { useAppGetters } from '@/storex/getters'

// 定义类型
interface ServiceItem {
  url: string
  name: string
}

interface StadiumDetails {
  imgStr: string
  stadiumName: string
  approval: number
  star: number
  stadiumTypeName: string
  workDate: string
  legalDate: string
  phone: string
  gdAddress: string
  enterpriseName: string
  stadiumType: string
  cancelHours: number
  writeMinutes: number
}

interface ProfileData {
  viewCount: number
  viewStatus: number
  viewRate: string
  orderCount: number
  orderStatus: number
  orderRate: string
  likeCount: number
  likeStatus: number
  likeRate: string
}

interface ReservateItem {
  id: number
  createTime: string
  orderPhone: string
  siteName: string
  orderNo: string
}

interface CommentItem {
  id: number
  headImg: string
  realName: string
  createTime: string
  star: number
  content: string
  imgs: any[]
}

interface SiteParams {
  date: string | null
  stadiumId: string | null
  type: string | null
}

// 组件引用
const siteBulletinRef = ref<InstanceType<typeof SiteBulletin> | null>(null)

// 路由相关
const route = useRoute()
const router = useRouter()

// Store getters
const store = useStore()
const detailFirstVisit = computed(() => store.state.app.detailFirstVisit)

// 响应式数据
const siteLoading = ref(false)
const stadiumId = ref<string | null>(null)
const details = reactive<StadiumDetails>({
  imgStr: '',
  stadiumName: '',
  approval: 0,
  star: 0,
  stadiumTypeName: '',
  workDate: '',
  legalDate: '',
  phone: '',
  gdAddress: '',
  enterpriseName: '',
  stadiumType: '',
  cancelHours: 0,
  writeMinutes: 0,
})
const serviceList = ref<ServiceItem[]>([])
const profileData = reactive<ProfileData>({
  viewCount: 0,
  viewStatus: 0,
  viewRate: '',
  orderCount: 0,
  orderStatus: 0,
  orderRate: '',
  likeCount: 0,
  likeStatus: 0,
  likeRate: '',
})
const reservateList = ref<ReservateItem[]>([])
const commentList = ref<CommentItem[]>([])
const weekList = ref<WeekDateItem[]>([])
const dateVal = ref('')
const todayDate = ref('')
const siteParams = reactive<SiteParams>({
  date: null,
  stadiumId: null,
  type: null,
})
const activeIndex = ref('0')
const showEditStadium = ref(false)
const showTipsModal = ref(false)
const tipCont = ref('')
const stadiumData = reactive({
  stadiumId: null as string | null,
  stadiumType: '',
  cancelHours: 0,
  writeMinutes: 0,
})

const { fromRoute } = useFromRoute()
// 生命周期钩子
onBeforeMount(() => {
  console.log(detailFirstVisit.value, 'detailFirstVisit', fromRoute.value?.name)
  if (
    fromRoute.value?.name == 'List' ||
    detailFirstVisit.value ||
    fromRoute.value?.name == 'Detail'
  ) {
    stadiumId.value = route.query.id as string
    if (siteBulletinRef.value) {
      siteBulletinRef.value.resetData()
    }
    fetchData()
  }
})

onBeforeRouteLeave((to: any, from: any, next: () => void) => {
  // 离开前缓存数据
  // this.$store.dispatch("app/setDefaultVisit", false)
  next()
})

// 方法定义
const fetchData = () => {
  console.log('刷新！！！')
  todayDate.value = dayjs((route.query.date as string) || new Date()).format('YYYY/MM/DD')
  dateVal.value = todayDate.value
  weekList.value = getWeekDates()
  getData()
  getDataProfile()
  getReservate()
  getComment()
}

// 获取场馆基础信息
const getData = async () => {
  console.log(stadiumId.value, 'stadiumId::')
  if (!stadiumId.value) return

  const { data } = await getStadiumById(stadiumId.value)
  Object.assign(details, data.stadiumBaseData)
  serviceList.value = data.serviceList
  // 从订单详情进入详情页时，默认选择订单中的场地类型
  const matchedType = data.siteTypeList.find(
    (item: any) => item.dictValue === route.query.type,
  )?.dictLabel
  siteParams.type = matchedType || data.siteTypeList?.[0]?.dictLabel || null

  stadiumData.stadiumId = stadiumId.value
  stadiumData.stadiumType = details.stadiumType
  stadiumData.cancelHours = details.cancelHours
  stadiumData.writeMinutes = details.writeMinutes

  nextTick(() => {
    if (siteBulletinRef.value) {
      siteBulletinRef.value.initData(data.siteTypeList)
    }
  })
}

// 获取场馆数据概况
const getDataProfile = async () => {
  if (!stadiumId.value) return

  const { data } = await getDataProfiling({
    dataType: 1,
    stadiumId: stadiumId.value,
  })
  Object.assign(profileData, data)
}

// 获取预约信息
const getReservate = async () => {
  if (!stadiumId.value) return

  const res = await getOrderListByStadiumId({ stadiumId: stadiumId.value })
  reservateList.value = res.rows
}

// 获取评论留言
const getComment = async () => {
  if (!stadiumId.value) return

  const res = await getEvaluateListByStadiumId({
    stadiumId: stadiumId.value,
  })
  commentList.value = res.rows
  commentList.value.forEach((item: any) => {
    item.imgs = item.img != '' ? item.img.split(',') : []
  })
}

// 数据概况/预约信息/评论留言查看更多
const handleMore = () => {
  router.push({
    path: '/stadium/data',
    query: { id: stadiumId.value },
  })
}

// 编辑场馆
const handleEditStadium = () => {
  showEditStadium.value = true
}

// 关闭修改场馆信息弹窗
const closeStadiumDialog = (val?: number) => {
  if (val == 1) {
    getData()
  } else {
    showEditStadium.value = false
  }
}

// 返回
const goBack = () => {
  router.go(-1)
}

// 初始化
stadiumId.value = route.query.id as string
todayDate.value = dayjs((route.query.date as string) || new Date()).format('YYYY/MM/DD')
</script>

<style lang="scss" scoped>
.wrap-container {
  overflow-x: hidden;
}
.stadium_detail {
  display: flex;
}
.stadium_info {
  background: #fff;
  padding: 0 15px 15px 15px;
  .stadium_img {
    img {
      width: 190px;
      height: 190px;
      border-radius: 11px;
    }
  }
  .stadium_cont {
    margin-left: 15px;
    flex: 1;
    .stadium_name {
      p {
        font-size: 18px;
        line-height: 27px;
      }
    }
    .auth_box {
      display: flex;
      align-items: center;
      font-size: 12px;
      color: #46a6ff;
      margin-left: 8px;
      img {
        width: 12px;
        height: 14px;
        margin-right: 4px;
      }
    }
    .edit {
      font-size: 14px;
      color: #2a82e4;
      display: flex;
      align-items: center;
      cursor: pointer;
      img {
        width: 15px;
        height: 15px;
        margin-right: 7px;
      }
    }
    .rate {
      :deep(.el-rate__icon) {
        font-size: 24px;
        margin-right: -3px;
      }
      :deep(.el-rate__text) {
        margin-left: 6px;
      }
    }
    .stadium_box {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
    }
    .info_item {
      display: flex;
      align-items: center;
      font-size: 14px;
      line-height: 21px;
      margin-top: 8px;
      p {
        color: #808080;
        display: flex;
        align-items: center;
        img {
          margin-right: 4px;
        }
      }
      .info_label {
        color: #383838;
        margin-right: 22px;
      }
    }
    .stadium_r {
      // margin-right: -48px;
      // width: 546px;
      .info_label {
        font-size: 14px;
        line-height: 21px;
        margin-right: 22px;
      }
    }
    .service_list {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      .service_item {
        margin-bottom: 16px;
        padding-right: 20px;
        .service_info {
          display: flex;
          align-items: center;
          p {
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;
            img {
              width: 100%;
            }
          }
          span {
            font-size: 14px;
            color: #015aff;
            display: block;
            line-height: 21px;
          }
        }
      }
    }
  }
}
.detail_l {
  flex: 1;
  width: 0;
  .detail_item {
    background: #fff;
    padding: 15px;
  }
}
.detail_r {
  width: 367px;
  .detail_item {
    background: #fff;
    padding: 15px 15px 20px;
  }
  .data_list {
    margin-top: 14px;
    .data_info {
      background: #f5faff;
      border-radius: 7px;
      padding: 7px 0 5px 8px;
      .data_label {
        font-size: 12px;
        font-weight: bold;
        line-height: 16px;
      }
      .data_num {
        font-size: 20px;
        color: #2a82e4;
        line-height: 24px;
        margin: 5px 0;
      }
      .compare {
        display: flex;
        align-items: center;
        font-size: 12px;
        p {
          display: flex;
          align-items: center;
          margin-left: 4px;
          span {
            &.up_style {
              color: #2a82e4;
            }
            &.drop_style {
              color: #d43030;
            }
          }
        }
      }
    }
  }
  .reservate_box {
    margin-top: 15px;
    .reservate_list {
      height: 55px;
      overflow-y: auto;
      .reservate_item {
        margin-top: 14px;
        font-size: 12px;
        line-height: 18px;
        .reservate_date {
          color: #808080;
        }
        .reservate_txt {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-top: 5px;
        }
      }
    }
  }
  .comment_box {
    margin-top: 15px;
    padding-bottom: 15px;
    max-height: 200px;
    overflow-y: auto;
    .comment_list {
      margin-top: 14px;
    }
    .comment_item {
      display: flex;
      &:not(:last-child) {
        margin-bottom: 25px;
      }
      .head_img {
        margin-right: 6px;
        img {
          width: 40px;
          height: 40px;
          border-radius: 5px;
        }
      }
      .comment_info {
        font-size: 12px;
        line-height: 18px;
        .comment_date {
          color: #a6a6a6;
        }
        .comment_rate {
          :deep(.el-rate__icon) {
            margin-right: -2px;
          }
        }
        .img_box {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          .img_item {
            margin-top: 11px;
          }
        }
      }
    }
  }
}
.detail_tit {
  line-height: 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .tit_name {
    display: flex;
    align-items: center;
    .line {
      width: 5px;
      height: 18px;
      background: #0988fb;
    }
    span {
      font-size: 16px;
      margin-left: 8px;
    }
  }
  p {
    font-size: 12px;
    color: #2a82e4;
    line-height: 18px;
    cursor: pointer;
  }
}
:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
  padding-right: 30px;
  .el-dialog__body {
    flex: 1;
    overflow: auto;
    padding-top: 20px;
    padding-left: 30px;
  }
  .dialog_btn {
    text-align: center;
    margin-top: 33px;
    .el-button {
      width: 90px;
      height: 38px;
      border-radius: 8px;
      & + .el-button {
        margin-left: 40px;
      }
      &.el-button--primary {
        background: #2a82e4;
      }
      &.el-button--default {
        background: #e5e5e5;
        color: #808080;
        border-color: #e5e5e5;
      }
    }
  }
  .el-date-editor,
  .el-select {
    width: 100%;
  }
}
:deep(.tip_dialog) {
  border-radius: 9px;
  padding-right: 0;
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding: 19px 24px 22px;
    color: #383838;
    .tip_tit {
      font-size: 20px;
      line-height: 29px;
    }
    .tip_cont {
      font-size: 16px;
      margin-top: 7px;
    }
    .tip_btn {
      text-align: right;
      margin-top: 28px;
      font-size: 16px;
      line-height: 24px;
      color: #008efa;
      cursor: pointer;
    }
  }
}
</style>
